﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.ComponentModel;

namespace LandingEagle.Domain
{
    public class FileDownloader
    {
        public FileDownloader(string uriFile, string saveDirectory)
        {
            _uriFile = uriFile;
            _saveDirectory = saveDirectory;
            webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(webClient_DownloadFileCompleted);
            
        }

        void webClient_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            _isStarted = false;
            _isDownloading = false;

            if (e.Cancelled || e.Error != null)
                _isDownloadSuccessful = false;

            else
                _isDownloadSuccessful = true;

        }

        #region Events
        public event DownloadProgressChangedEventHandler DownloadProgressChanged
        {
            add
            {
                webClient.DownloadProgressChanged += value;
            }
            remove
            {
                webClient.DownloadProgressChanged -= value;
            }
        }

        public event AsyncCompletedEventHandler DownloadFileCompleted
        {
            add
            {
                webClient.DownloadFileCompleted += value;
            }
            remove
            {
                webClient.DownloadFileCompleted -= value;
            }
        }
        #endregion

        #region Fields
        private string _uriFile = string.Empty;
        private string _saveDirectory = string.Empty;
        private WebClient webClient = new WebClient();
        private bool _isStarted = false;
        private bool _isDownloading = false;
        private bool _isDownloadSuccessful = false;

        #endregion

        #region Properties

        public bool IsStarted
        {
            get { return _isStarted; }
        }

        public bool IsDownloading
        {
            get { return _isDownloading; }
        }

        public bool IsDownloadSuccessful
        {
            get { return _isDownloadSuccessful; }
        }

        #endregion

        #region Methods

        public void StartDownload()
        {
            _isDownloading = true;
            _isStarted = true;
            _isDownloadSuccessful = false;

            try
            {
                webClient.DownloadFileAsync(new Uri(_uriFile), _saveDirectory,DateTime.Now);
            }
            catch (WebException wex)
            {
                //Disparar para evento.
            }
            catch (InvalidOperationException iex)
            {
                //Disparar para evento.
            }
        }

        #endregion

    }
}
